from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api import deps
from app.schemas import customer
from app.database.models.erp import CustomerProfile, CustomerTelNo
from app.database.models.base import User

router = APIRouter()

@router.get("/{customer_id}/tel-nos", response_model=List[customer.CustomerTelNo])
def list_customer_tel_nos(
    customer_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取指定客户的所有联系方式"""
    try:
        # 检查客户是否存在
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == customer_id
        ).first()
        if not customer_obj:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 获取联系方式列表
        tel_nos = db.query(CustomerTelNo).filter(
            CustomerTelNo.customer_profile_id == customer_id
        ).all()
        return tel_nos
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/{customer_id}/tel-nos", response_model=customer.CustomerTelNo)
def create_customer_tel_no(
    *,
    db: Session = Depends(deps.get_db),
    customer_id: int,
    tel_no_in: customer.CustomerTelNoCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """为客户添加新的联系方式"""
    try:
        # 检查客户是否存在
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == customer_id
        ).first()
        if not customer_obj:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 创建新联系方式
        tel_no = CustomerTelNo(
            customer_profile_id=customer_id,
            **tel_no_in.dict(exclude={'customer_profile_id'})
        )
        db.add(tel_no)
        db.commit()
        db.refresh(tel_no)
        return tel_no
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/tel-nos/{tel_no_id}", response_model=customer.CustomerTelNo)
def update_customer_tel_no(
    *,
    db: Session = Depends(deps.get_db),
    tel_no_id: int,
    tel_no_in: customer.CustomerTelNoUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新客户联系方式"""
    try:
        # 获取联系方式记录
        tel_no = db.query(CustomerTelNo).filter(CustomerTelNo.ID == tel_no_id).first()
        if not tel_no:
            raise HTTPException(status_code=404, detail="Contact not found")

        # 检查权限
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == tel_no.customer_profile_id
        ).first()
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新联系方式
        for field, value in tel_no_in.dict(exclude_unset=True).items():
            setattr(tel_no, field, value)

        db.add(tel_no)
        db.commit()
        db.refresh(tel_no)
        return tel_no
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/tel-nos/{tel_no_id}")
def delete_customer_tel_no(
    *,
    db: Session = Depends(deps.get_db),
    tel_no_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除客户联系方式"""
    try:
        # 获取联系方式记录
        tel_no = db.query(CustomerTelNo).filter(CustomerTelNo.ID == tel_no_id).first()
        if not tel_no:
            raise HTTPException(status_code=404, detail="Contact not found")

        # 检查权限
        customer_obj = db.query(CustomerProfile).filter(
            CustomerProfile.ID == tel_no.customer_profile_id
        ).first()
        if current_user.role != "admin" and customer_obj.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 删除联系方式
        db.delete(tel_no)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 